#!/usr/bin/env python
# -*- coding:UTF-8 -*-
# Project: devops
#  Author: an00
#  Create: 2018/6/24 9:30

import io
from paramiko.rsakey import RSAKey
from rest_framework import serializers
from django.contrib.auth.models import Group
from django.contrib.auth import get_user_model
User = get_user_model()


class UserSerializer(serializers.ModelSerializer):
    """
    用户的序列化类，包括创建、删除、修改等
    """
    username = serializers.CharField(required=False, read_only=False, max_length=32, label="用户名", help_text="用户名")
    name = serializers.CharField(required=False, read_only=False, label="姓名", help_text="姓名")
    is_active = serializers.BooleanField(required=False, label="登陆状态", help_text="登陆状态")
    email = serializers.CharField(required=False, help_text="联系邮箱")
    last_login = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", read_only=True, help_text="上次登录时间")
    phone = serializers.CharField(required=False, max_length=11, min_length=11, allow_null=True, help_text="手机号",
                                  error_messages={"max_length": "手机号错误", "min_length": "手机号错误"})
    password = serializers.CharField(min_length=8, label='密码', help_text='密码',
                                     write_only=True, style={"input_type": "password"})
    role = serializers.CharField(default='ordinary', help_text='角色类型')
    groups = serializers.PrimaryKeyRelatedField(many=True, help_text='组列表', queryset=Group.objects.all())

    def create(self, validated_data):
        user = super(UserSerializer, self).create(validated_data=validated_data)
        user.set_password(validated_data['password'])
        user.id_rsa_key, user.id_rsa_pub = self.get_sshkey(validated_data['email'])
        user.save()
        return user

    def update(self, instance, validated_data):
        """
        更新密码
        """
        password = validated_data.pop('password', None)
        instance = super(UserSerializer, self).update(instance, validated_data)
        if password:
            instance.set_password(password)
            instance.save()
        return instance

    @staticmethod
    def get_sshkey(email):
        """
        为用户生成rsa密钥对
        """
        output = io.StringIO()
        sbuffer = io.StringIO()
        key = RSAKey.generate(2048)
        key.write_private_key(output)
        private_key = output.getvalue()

        sbuffer.write("{} {} {}".format(key.get_name(), key.get_base64(), email))
        public_key = sbuffer.getvalue()
        return private_key, public_key

    class Meta:
        model = User
        fields = ("id", "username", "name", "phone", "email", "is_active", "last_login", "role", "groups", "password")


class GroupSerializer(serializers.ModelSerializer):
    """
    用户组序列化
    """

    def to_representation(self, instance):
        ret = super(GroupSerializer, self).to_representation(instance)
        member = instance.user_set.count()
        ret['member'] = member
        ret['users'] = [{'id': i.id, 'name': i.name, 'username': i.username} for i in instance.user_set.all()]
        return ret

    class Meta:
        model = Group
        fields = '__all__'


class UserGroupSerializer(serializers.ModelSerializer):
    """
    用户所属组序列化类
    """

    groups = GroupSerializer(many=True)

    def to_representation(self, instance):
        result = super(UserGroupSerializer, self).to_representation(instance)
        result['name'] = instance.name
        return result

    class Meta:
        model = User
        fields = ('id', 'username', 'groups')
